#include "Globals.h"
#include "cShader.h"


cShader::cShader(void)
{
}

cShader::cShader(char* pathVert, char* pathFrag)
{
	this->pathVert = pathVert;
	this->pathFrag = pathFrag;
	initShader();
	linkProgram();
}


cShader::~cShader(void)
{
}

char *file2string(const char *path)
{
        FILE *fd;
        long len, r;
        char *str;

        if (!(fd = fopen(path, "r")))
        {
                fprintf(stderr, "Can't open file '%s' for reading\n", path);
                return NULL;
        }

        fseek(fd, 0, SEEK_END);
        len = ftell(fd);

        //printf("File '%s' is %ld long\n", path, len);

        fseek(fd, 0, SEEK_SET);

        if (!(str = (char*)malloc(len * sizeof(char))))
           {
              fprintf(stderr, "Can't malloc space for '%s'\n", path);
              return NULL;
           }

        r = fread(str, sizeof(char), len, fd);

        str[r - 1] = '\0'; /* Shader sources have to term with null */

        fclose(fd);

        return str;
}

void cShader::initShader(){
	GLchar *sourceVertexShader;
    GLchar *sourceFragmentShader;
    sourceVertexShader=(GLchar*)file2string(pathVert);
    sourceFragmentShader=(GLchar*)file2string(pathFrag);

	vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShaderID, 1, (const GLchar**)&sourceVertexShader, 0);
    glCompileShader(vertexShaderID);

    fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShaderID, 1, (const GLchar**)&sourceFragmentShader, 0);
    glCompileShader(fragmentShaderID);
}

void cShader::linkProgram(){
	programID = glCreateProgram();
    glAttachShader(programID, vertexShaderID);
    glAttachShader(programID, fragmentShaderID);
    glLinkProgram(programID);
}

void cShader::use(){
	glUseProgram(programID);
}

void cShader::activeShader(char* pathVert, char* pathFrag){
	this->pathVert = pathVert;
	this->pathFrag = pathFrag;
	initShader();
	linkProgram();
}

GLuint cShader::getID(){
	return programID;
}